<?php

namespace App\Http\Controllers\Admin\LuckyTree;

use App\Enums\CriticalEnum;
use Carbon\Carbon;
use App\Enums\LuckyTree;
use App\Response\Response;
use App\Exceptions\BasicException;
use Illuminate\Support\Facades\DB;
use \App\Http\Controllers\BaseController;
use Illuminate\Http\Request;

class LuckyTreeController extends BaseController
{
    public function __construct(Request $request)
    {
        $this->is_next = $request->input('is_next', 0);
        if (!in_array($this->is_next, [0, 1])) {
            throw new BasicException(0, '参数有误');
        }
        $this->pot_name = '';
        if ($this->is_next) {
            $this->type = $request->input('type', LuckyTree::POOL_TYPE_HUNDRED_NEXT);
            if (isset(LuckyTree::POOL_TYPE_CONFIG_NEXT[$this->type])) {
                $this->pot_name = LuckyTree::POOL_TYPE_CONFIG_NEXT[$this->type];
            }
        } else {
            $this->type = $request->input('type', LuckyTree::POOL_TYPE_HUNDRED);
            if (isset(LuckyTree::POOL_TYPE_CONFIG[$this->type])) {
                $this->pot_name = LuckyTree::POOL_TYPE_CONFIG[$this->type];
            }
        }
    }

    /**
     * @api {get} lucky/tree 本期奖池
     * @apiDescription type:1,2,3,4,5分别对应本期奖池的1连奖池,10连奖池,100连奖池,新手奖池,独立奖池;11,12,13,14,15分别对应下期奖池的1连奖池,10连奖池,100连奖池,新手奖池,独立奖池;30特殊奖池
     * @apiVersion 0.1.0
     * @apiName 本期奖池
     * @apiGroup 幸运树
     * @apiParam {numeric} type   奖池类型,非必传
     * @apiParam {numeric} is_next   是否下期奖池1是0否,默认0,非必传
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": {
     * "left 剩余礼物数量": "50000",
     * "total 剩余礼物总金额": "9599738",
     * "type 奖池类型": "11",
     * "name 奖池名称": "1连奖池",
        "critical_gift_ids 暴击奖池礼物(需要判断是否可设置暴击数量)": [
        542,
        543
        ],
     * "list": [
     * {
     * "id": 30,
     * "gift_id": 106,
     * "number 库存": 11900,
     * "critical_times 暴击数量": 11900,
     * "ratio 爆率": 0,
     * "gift_name 礼物名称": "棒棒糖",
     * "price 价格": 10,
     * "picture 图片": "https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/user-dir/FdpaWETQx8.png",
     * "special 特效": "https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/user-dir/e7SGifpTPX.png",
     * "quality 礼物品质": "白色"
     * }
     * ]
     * }
     * }
     */
    public function index(Request $request)
    {
        $list = app('repo_lucky_tree')->getJackpotList($this->type, $this->is_next);

        $criticalGifts = app('model_critical_prize')->getModuleGiftIds(CriticalEnum::MODULE_TREE);

        return Response::sendData([
            'left'  => app('repo_lucky_tree')->getJackpotCount($this->type, $this->is_next),
            'total' => app('repo_lucky_tree')->getJackpotTotal($this->type, $this->is_next),
            'type'  => $this->type,
            'name'  => $this->pot_name,
            'list'  => $list,
            'critical_gift_ids'  => $criticalGifts,
        ]);
    }

    /**
     * @api {post} lucky/tree 添加修改本期奖池礼物
     * @apiVersion 0.1.0
     * @apiName 添加修改本期奖池礼物
     * @apiGroup 幸运树
     * @apiParam {numeric} type   奖池类型,非必传
     * @apiParam {numeric} is_next   是否下期奖池1是0否,默认0,非必传
     * @apiParam {numeric} id   如果传了id则为更新,否则添加,非必传
     * @apiParam {numeric} number   库存,必传
     * @apiParam {numeric} gift_id   礼物id,必传
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": "success"
     * }
     */
    public function update(Request $request)
    {
        $data = $request->only(['gift_id', 'number']);
        $id = intval($request->input('id', 0));
        if (!isset($data['gift_id']) || $data['gift_id'] <= 0) {
            throw new BasicException(0, '请选择礼物');
        }
        if (!isset($data['number']) || $data['number'] < 0) {
            throw new BasicException(0, '数量不能小于0');
        }
        $model = $this->is_next ? 'model_lucky_tree_next' : 'model_lucky_tree';
        if ($id > 0) {
            app($model)->where('id', $id)->update($data);
        } else {
            $data['type'] = $this->type;
            if (!$this->is_next) {
                $data['add_time'] = Carbon::now();
            }
            app($model)->insert($data);
        }

        return Response::sendData('success');
    }

    /**
     * @api {post} lucky/tree/all 一键修改本期奖池礼物
     * @apiVersion 0.1.0
     * @apiName 一键修改本期奖池礼物
     * @apiGroup 幸运树
     * @apiParam {numeric} type   奖池类型,非必传 1,2,3,4,5分别对应本期奖池的1连奖池,10连奖池,100连奖池,新手奖池,独立奖池;11,12,13,14,15分别对应下期奖池的1连奖池,10连奖池,100连奖池,新手奖池,独立奖池;30特殊奖池
     * @apiParam {numeric} is_next   是否下期奖池1是0否,默认0,非必传
     * @apiParam {numeric} gift_detail   礼物数据json  [{"gift_id":377,"gift_name":"拐杖糖","number":2301,"ratio":0}]
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": "success"
     * }
     */
    public function editAll(Request $request)
    {
        $v = app('validator')->make($request->all(),
            [
                'gift_detail' => 'required|string',
            ]);
        if ($v->fails()) {
            throw new BasicException(10001, getValidateMessage($v->messages()));
        }
        $data = $request->only(['gift_detail']);
        $giftDetailStr = $data['gift_detail'];
        $giftDetailList = json_decode($giftDetailStr, 1);
        $model = $this->is_next ? 'model_lucky_tree_next' : 'model_lucky_tree';
        foreach ($giftDetailList as $key => $value) {
            if (!isset($value['gift_id']) || $value['gift_id'] <= 0) {
                throw new BasicException(0, '请选择礼物');
            }
            if ($value['number'] < 0) {
                throw new BasicException(0, '数量不能小于0');
            }
            if ($value['ratio'] < 0) {
                throw new BasicException(0, '爆率不能小于0');
            }
            $whereArr = [];
            $whereArr[] = ["gift_id", "=", $value['gift_id']];
            $whereArr[] = ["type", "=", $this->type];
            app($model)->where($whereArr)->update(['number' => $value['number'], 'ratio' => $value['ratio']]);
        }

        return Response::sendData('success');
    }

    /**
     * @api {delete} lucky/tree 删除本期奖池礼物
     * @apiVersion 0.1.0
     * @apiName 删除本期奖池礼物
     * @apiGroup 幸运树
     * @apiParam {numeric} id   主键id,必传
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": "success"
     * }
     */
    public function delete(Request $request)
    {
        $id = $request->input('id', 0);
        $model = $this->is_next ? 'model_lucky_tree_next' : 'model_lucky_tree';
        $detail = app($model)->where('id', $id)->first();
        if (!$detail) {
            throw new BasicException(0, '数据有误');
        }
        app($model)->where('id', $id)->delete();

        return Response::sendData('success');
    }

    /**
     * @api {get} lucky/tree/record 中奖纪录
     * @apiVersion 0.1.0
     * @apiName 中奖纪录
     * @apiGroup 幸运树
     * @apiParam {numeric} page   page,非必传
     * @apiParam {numeric} perPage   perPage,非必传
     * @apiParam {string} datemin   开始时间如2021-03-11,非必传
     * @apiParam {string} datemax   结束时间如2021-03-12,非必传
     * @apiParam {number} gift_id   礼物id,非必传
     * @apiParam {string} keyword   用户编号或昵称,非必传
     * @apiParam {int} is_flutter 是否飘屏记录，1：是，0：否，-1（默认）：全部
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": {
     * "list": [
     * {
     * "id": 25682,
     * "user_id": 547900,
     * "gift_id": 382,
     * "add_time": 1614653769,
     * "number": 1,
     * "nickname": "提莫队长呢",
     * "gift_name": "2021发大财",
     * "gift_price": 666, 礼物价值（单位：气泡币）
     * "user_code": 617040
     * }
     * ],
     * "meta": {
     * "page": 1,
     * "limit": 15,
     * "next": "http://www.na.com/lucky/tree/record?page=2",
     * "total": 828
     * }
     * }
     * }
     */
    public function record(Request $request)
    {
        $list = app('repo_lucky_tree')->getRecord($request);

        //        return Response::sendList($list);
        return Response::sendData($list);
    }

    /**
     * @api {post} lucky/tree/replace 替换奖池
     * @apiVersion 0.1.0
     * @apiName 替换奖池
     * @apiGroup 幸运树
     * @apiParam {numeric} type   奖池类型,必传
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": "success"
     * }
     */
    public function replace()
    {
        app('repo_lucky_tree')->replaceJackpot($this->type);

        return Response::sendData(1);
    }

    /**
     * @api {get} lucky/tree/special 特殊奖池列表
     * @apiVersion 0.1.0
     * @apiName 特殊奖池列表
     * @apiGroup 幸运树
     * @apiParam {numeric} type   奖池类型,固定值,传30,必传
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": {
     * "type": "30",
     * "name": "特殊奖池",
     * "ratio": {
     * "theory 理论上": {
     * "times 理论次数": 101001299,
     * "in_coin 理论金币数": 20200259800,
     * "out_coin 产出": 52786673804500,
     * "ratio 产出比": 2613.17
     * },
     * "all": {
     * "in_coin": "2206600 + 1618800",
     * "out_coin": "9246640 + 78855415",
     * "ratio": 23.03
     * },
     * "current 实际上": {
     * "times 实际次数": "82618",
     * "in_coin 实际金币": "16523600",
     * "out_coin 实际产出金币": "97895349",
     * "ratio 实际投入产出比": 5.92
     * },
     * "ratio_config": {
     * "min_ratio 库存产出投入比最低下限": 0.95,
     * "max_ratio 库存产出投入比最大上限": 0.8,
     * "min_self_ratio 个人产出投入比最低下限": 0.7,
     * "max_self_ratio 个人产出投入比最大上限": 1.15
     * }
     * },
     * "list": [
     * {
     * "id": 57,
     * "gift_id": 382,
     * "number 权重": 100,
     * "ratio": 0,
     * "gift_name": "2021发大财",
     * "price 价格(金币)": 1,
     * "picture": "http://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/admin_images/5feae4dde6f7d.png",
     * "special": "http://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/admin_images/5feae4dfd040a.png",
     * "quality 品质": "白色",
     * "key 修正序号": 1,
     * "count 中奖个数": "8894"
     * }
     * ]
     * }
     * }
     */
    public function special()
    {
        if ($this->type != 30) {
            throw new BasicException(0, '非法访问');
        }
        $data = app('repo_lucky_tree')->getJackpotList($this->type, $this->is_next);
        // 查询中奖礼物数
        $giftIds = $data->pluck('gift_id');
        if (!empty($giftIds)) {
            $result = DB::table('ln_lucky_tree_user_record_special')
                ->whereIn('gift_id', $giftIds)
                ->selectRaw('sum(number) as count,gift_id')
                ->groupBy('gift_id')
                ->get()->toArray();
            $map = array_column($result, 'count', 'gift_id');
            foreach ($data as &$value) {
                $value->count = $map[$value->gift_id] ?? 0;
            }
        }

        $ratioConfig = app('repo_lucky_tree')->specialGiftList(['type' => 30]);

        return Response::sendData([
            'type'  => $this->type,
            'name'  => $this->pot_name,
            'ratio' => $ratioConfig,
            'list'  => $data,
        ]);
    }

    /**
     * @api {post} lucky/tree/ratio 更新产出比
     * @apiVersion 0.1.0
     * @apiName 更新产出比
     * @apiGroup 幸运树
     * @apiParam {numeric} min_ratio   库存产出投入比最低下限,必传
     * @apiParam {numeric} max_ratio   库存产出投入比最大上限,必传
     * @apiParam {numeric} min_self_ratio   个人产出投入比最低下限,必传
     * @apiParam {numeric} max_self_ratio   个人产出投入比最大上限,必传
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": "success"
     * }
     */
    public function updateRatio(Request $request)
    {
        $key = 'fish:ratio_config';
        $minRatio = $request->input('min_ratio');
        $maxRatio = $request->input('max_ratio');
        $minSelfRatio = $request->input('min_self_ratio');
        $maxSelfRatio = $request->input('max_self_ratio');
        if ($minRatio <= 0 || $maxRatio <= 0 || $minSelfRatio <= 0 || $maxSelfRatio <= 0) {
            throw new BasicException(0, '概率配置不能小于等于0');
        }
        $redis = app('redis');
        $ratioConfig = [
            'min_ratio'      => $minRatio,
            'max_ratio'      => $maxRatio,
            'min_self_ratio' => $minSelfRatio,
            'max_self_ratio' => $maxSelfRatio,
        ];
        $redis->set($key, json_encode($ratioConfig));

        return Response::sendData(1);
    }

    /**
     * @api {get} lucky/tree/user/ratio 用户产出比列表
     * @apiVersion 0.1.0
     * @apiName 用户产出比列表
     * @apiGroup 幸运树
     * @apiParam {number} user_code 用户编号,非必传
     * @apiParam {number} nickname 用户昵称
     * @apiParam {number} mobile 用户编号,非必传
     * @apiParam {number} type 用户编号,非必传 与output配合使用 实际产出比 筛选 1:>output  2:<output 3：=output
     * @apiParam {number} output 用户编号,非必传
     * @apiParam {number} output_order 1根据id排序 2根据实际投入产出比 升序 3根据实际投入产出比 降序
     * @apiParam {string} last_lottery_time_start 最后抽奖时间开始
     * @apiParam {string} last_lottery_time_end 最后抽奖时间结束
     * @apiParam {number} perPage 页码 ，非必传 默认20
     * @apiParam {number} page 用户编号,非必传
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": {
     * "list": [
     * {
     * "current_ratio_real": "0.0500",//实际产出比
     * "id": 188,
     * "mobile": "16208562044",
     * "incoin_total": 200,
     * "outcoin_total": 10,
     * "nickname": "气泡用户192948",
     * "head_picture": "https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/custom/default_avatar.png",
     * "user_code": 192948,
     * "current_incoin_total": 200,
     * "current_outcoin_total": 10,
     * "current_ratio": 0.05//计算后产出比
     * },
     * {
     * "current_ratio_real": "0.0500",
     * "id": 217,
     * "mobile": "15008562046",//用户电话
     * "incoin_total": 200,
     * "outcoin_total": 10,
     * "nickname": "气泡用户3",
     * "head_picture": "https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/custom/default_avatar.png",
     * "user_code": 887504,
     * "current_incoin_total": 200,
     * "current_outcoin_total": 10,
     * "current_ratio": 0.05
     * }
     * ],
     * "meta": {
     * "page": 1,
     * "limit": 20,
     * "next": "http://qipaomanage.com/lucky/tree/user/ratio?page=2",
     * "total": 471
     * },
     * "header": {
     * "user_incoin": 20000,
     * "user_outcoin": 20000
     * }
     * }
     * }
     */
    public function userRatio(Request $request)
    {
        $keyword = $request->input('user_code');
        $nickname = $request->input('nickname', null);
        $mobile = $request->input('mobile', null);
        $output = $request->input('output', null);
        $type = $request->input('type', null);             //>= or <=
        $ordertype = $request->input('output_order', 1);   //>= or <=
        $lastLotteryTimeStart = $request->input('last_lottery_time_start', '');
        $lastLotteryTimeEnd = $request->input('last_lottery_time_end', '');
        $page = $request->input('page', 20);               //>= or <=
        $perPage = $request->input('perPage', 20);
        $data = $request->only(['user_code', 'nickname', 'mobile', 'output', 'type', 'output_order', 'perPage']);
        $va = app('validator')->make($data, [
            'perPage'      => 'integer|min:1',
            'page'         => 'integer|min:1',
            'user_code'    => 'integer|min:1',
            'mobile'       => 'string|max:11',
            'output_order' => 'in:1,2,3',//根据id排序 2根据实际投入产出比 升序 3根据实际投入产出比 降序
            'output'       => 'numeric|min:0',
            'type'         => 'integer|in:1,2,3',//1:> 2:< 3:=

        ]);
        if ($va->fails()) {
            throw  new BasicException(10001, $va->errors()->first());
        }

        $where = [
            ['base.id', '>', 0],
        ];
        if ($keyword) {
            $where[] = ['ud.user_code', '=', $keyword];
        }
        if ($nickname) {
            $where[] = ['ud.nickname', 'like', '%' . $nickname . "%"];
        }
        if ($mobile) {
            $where[] = ['u.mobile', '=', $mobile];
        }


        if ($type && $type == 1 && $output) {
            $where[] = [DB::raw("ROUND(base.outcoin_total/base.incoin_total,2)"), '>', intval($output)];
        }
        if ($type && $type == 2 && $output) {
            $where[] = [DB::raw("ROUND(base.outcoin_total/base.incoin_total,2)"), '<', $output];
        }
        if ($type && $type == 3 && $output) {
            $where[] = [DB::raw("ROUND(base.outcoin_total/base.incoin_total,2)"), '=', $output];
        }
        if ($lastLotteryTimeStart) {
            $where[] = ['base.update_time', '>=', $lastLotteryTimeStart];
        }
        if ($lastLotteryTimeEnd) {
            $where[] = ['base.update_time', '<=', $lastLotteryTimeEnd];
        }

        $order = [];
        if ($ordertype == 1) {
            $order['field'] = 'base.id';
            $order['way'] = 'desc';
        } elseif ($ordertype == 2) {
            $order['field'] = 'current_ratio_real';
            $order['way'] = 'asc';
        } else {
            $order['field'] = 'current_ratio_real';
            $order['way'] = 'desc';
        }

        $field = [
            DB::raw('ROUND(base.outcoin_total/base.incoin_total,2) as current_ratio_real'),
            'base.id',
            'u.mobile',
            'base.incoin_total',
            'base.outcoin_total',
            'ud.nickname',
            'ud.head_picture',
            'ud.user_code',
        ];

        $list = DB::table('ln_lucky_tree_user_record as base')
            ->leftJoin('ln_user_data as ud', 'base.user_id', '=', 'ud.user_id')
            ->leftJoin('ln_user as u', 'base.user_id', '=', 'u.user_id')
            ->select($field)
            ->where($where)
            ->orderBy($order['field'], $order['way'])
            ->paginate($perPage);

        $userRatioConfigKey = 'fish:user_ratio_config';
        $redis = app('redis');
        $userRatioConfig = $redis->get($userRatioConfigKey);

        if (empty($userRatioConfig)) {
            $userRatioConfig = [
                'user_incoin'  => 20000,
                'user_outcoin' => 20000,
            ];
            $redis->set($userRatioConfigKey, json_encode($userRatioConfig));
        } else {
            $userRatioConfig = json_decode($userRatioConfig, true);
        }

        $list->getCollection()->transform(function ($value) use ($userRatioConfig) {
            if ($value->incoin_total > 2 * $userRatioConfig['user_incoin'] && $value->outcoin_total > 2 * $userRatioConfig['user_outcoin']) {//用户投入产出都在计划的两倍以上
                $timesIncoin = ceil($value->incoin_total / $userRatioConfig['user_incoin']);                                                 //用户实际投入/计划投入 倍率
                $timesOutcoin = ceil($value->outcoin_total / $userRatioConfig['user_outcoin']);
                $times = min($timesIncoin, $timesOutcoin);
                $value->current_incoin_total = $value->incoin_total - ($times - 2) * $userRatioConfig['user_incoin'];
                $value->current_outcoin_total = $value->outcoin_total - ($times - 2) * $userRatioConfig['user_outcoin'];
                $value->current_ratio = round($value->current_outcoin_total / $value->current_incoin_total, 2);
//                $value->current_ratio_real = round($value->current_ratio_real , 2);
            } else {
                $value->current_incoin_total = $value->incoin_total;
                $value->current_outcoin_total = $value->outcoin_total;
                $value->current_ratio = $value->current_incoin_total == 0 ? 0 : round($value->current_outcoin_total / $value->current_incoin_total, 2);
//                $value->current_ratio_real = round($value->current_ratio_real , 2);
            }

            return $value;
        });

        return Response::sendList($list, [], $userRatioConfig);
    }

    /**
     * @api {post} lucky/tree/user/ratio 用户投入产出比配置修改
     * @apiVersion 0.1.0
     * @apiName 用户投入产出比配置修改
     * @apiGroup 幸运树
     * @apiParam {numeric} user_incoin   用户理论投入,必传
     * @apiParam {numeric} user_outcoin   用户理论产出,必传
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": "success"
     * }
     */
    public function updateUserRatio(Request $request)
    {
        $key = 'fish:user_ratio_config';
        $userIncoin = $request->input('user_incoin');
        $userOutcoin = $request->input('user_outcoin');
        if ($userIncoin <= 0 || $userOutcoin <= 0) {
            throw new BasicException(0, '投入及产出配置不能小于等于0');
        }
        $redis = app('redis');
        $userRatioConfig = [
            'user_incoin'  => $userIncoin,
            'user_outcoin' => $userOutcoin,
        ];
        $redis->set($key, json_encode($userRatioConfig));

        return Response::sendData(1);
    }

    /**
     * @api {get} lucky/tree/independent 独立奖池
     * @apiVersion 0.1.0
     * @apiName 独立奖池
     * @apiGroup 幸运树
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": [
     * {
     * "nickname": "咪咪咪咪咪咪咪咪咪咪",
     * "user_code": 731183,
     * "head_picture": "https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/custom/default_avatar.png",
     * "threshold 移除阈值": 100000000,
     * "earn_coin 当前收益": -62780,
     * "add_time": 1608358881,
     * "state": 1,
     * "id": 8,
     * "type": 4
     * },
     * {
     * "nickname": "瑞瑞瑞瑞瑞瑞瑞瑞瑞r",
     * "user_code": 679883,
     * "head_picture": "https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/ios_images/2020-12-07/705B262C-DADC-4BC0-9B57-0635EC4BD655.jpeg",
     * "threshold": 10000,
     * "earn_coin": -570,
     * "add_time": 1610507589,
     * "state": 1,
     * "id": 10,
     * "type": 4
     * }
     * ]
     * }
     */
    public function independent()
    {
        $where['state'] = 1;
        $list = DB::table('ln_lucky_tree_special_user as a')
            ->select([
                'b.nickname',
                'b.user_code',
                'b.head_picture',
                'a.threshold',
                'a.earn_coin',
                'a.add_time',
                'a.state',
                'a.id',
                'a.type',
            ])
            ->leftJoin('ln_user_data as b', 'a.user_id', '=', 'b.user_id')
            ->where('state', 1)->get();

        return Response::sendData($list);
    }

    /**
     * @api {post} lucky/tree/independent 修改独立奖池
     * @apiVersion 0.1.0
     * @apiName 修改独立奖池
     * @apiGroup 幸运树
     * @apiParam {number} user_code 用户编号,必传
     * @apiParam {number} threshold 阀值,必传
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": 1
     * }
     */
    public function updateIndependent(Request $request)
    {
        $data = $request->only(['user_code', 'threshold']);
        if (!isset($data['user_code']) || !$data['user_code']) {
            throw new BasicException(0, '请输入用户id');
        }
        if (!isset($data['threshold']) || !$data['threshold']) {
            throw new BasicException(0, '请输入阈值');
        }
        if ($data['threshold'] <= 0) {
            throw new BasicException(0, '阈值必须大于0');
        }
        $user = app('model_user_data')->where('user_code', $data['user_code'])->first();
        if (!$user) {
            throw new BasicException(0, '用户不存在');
        }

        DB::table('ln_lucky_tree_special_user')->where('user_id', $user->user_id)->delete();
        DB::table('ln_lucky_tree_special_user')->insert([
            'user_id'   => $user->user_id,
            'threshold' => $data['threshold'],
            'add_time'  => Carbon::now()->timestamp,
        ]);

        return Response::sendData(1);
    }

    /**
     * @api {delete} lucky/tree/independent 删除独立奖池用户
     * @apiVersion 0.1.0
     * @apiName 删除独立奖池用户
     * @apiGroup 幸运树
     * @apiParam {number} id id,必传
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": 1
     * }
     */
    public function deleteIndependent(Request $request)
    {
        $id = $request->input('id');
        if (!$id) {
            throw new BasicException(10001);
        }
        $detail = DB::table('ln_lucky_tree_special_user')->where('id', $id)->first();
        if (!$detail) {
            throw new BasicException(10008);
        }
        DB::table('ln_lucky_tree_special_user')->where('id', $id)->delete();

        return Response::sendData(1);
    }
}
